#!/usr/bin/perl
use CGI;
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use strict;
use Digest::MD5 qw(md5 md5_hex md5_base64);
my $readin;
read(STDIN, $readin, $ENV{'CONTENT_LENGTH'});
my $inputstring = $readin;
my $schar = substr($inputstring, 1, 1);

my %hash = ();


if($ENV{'CONTENT_LENGTH'}.length() < 1){
#####If nothing is typed right now.#####
	print "Content-type: text/html\n\n";
	print $inputstring; 
	open (FILE,"login.html");
	while (<FILE>) {
		print $_;
	}
	close(FILE);
print <<END_OF_PRINTING; 
END_OF_PRINTING
}
elsif ($schar ne 's'){
	my ($pairs,$key,$value);
	my @pairsarr = split(/&/, $inputstring);
	foreach my $pairs (@pairsarr){
		my @keyvalue = split(/=/, $pairs);
		$key = $keyvalue[0];
		$value = $keyvalue[1];
		$hash{ $key } = $value; 
		open (FILE2, ">>url_sub.txt");
		print FILE2 $value;
		print FILE2 "\n";
		close (FILE2); 	
	}
	print "Content-type: text/html\n\n";
	print $inputstring; 
	print "printed $value";
}
else{
	#gets the username and password and gets it ready to be checked
	print "Content-type: text/html\n\n";
	my ($pairs,$key,$value);
	my @pairsarr = split(/&/, $inputstring);
	foreach my $pairs (@pairsarr){
		my @keyvalue = split(/=/, $pairs);
		$key = $keyvalue[0];
		$value = $keyvalue[1];
		$hash{ $key } = $value;
	}
	my $username = $hash{"username"};
		$username =~ s/%40/at/g;
	my $password = $hash{"password"};
	
	my $trial = "$username".",".md5_hex($password);

	my $file;
	my $fp;
	my @arr;
	my @lines;
	

$file= "password.txt";

open($fp,$file);

@arr = <$fp>;

@lines = grep /$trial/, @arr;

close($fp);

my $q = new CGI;
my $ip = $q->remote_host();
if (@lines) {
	system("/usr/bin/perl ./schedule.pl $username");
	#login success
	system("./stats.pl -l $username");
	system("echo $ip success >> loginlog.txt");
open (FILE,"appointment.html");
				while (<FILE>) {
					print $_;
				}
				print '<INPUT TYPE="text" name="username" id="username" value="'.$username.'"\>';
				close(FILE);
} else {
	system("echo $ip failed >> loginlog.txt");
	system("./stats.pl -a $username");
	#login failed
  print "not found";
  print $trial;
}
	my $check;
	my $found;
	my ($pairs,$key,$value);
	my $count;
	my @pairsarr = split(/&/, $inputstring);
	print $inputstring;
	foreach my $pairs (@pairsarr){
		
		
		$count = $count + 1;
		print $pairs;
		my @keyvalue = split(/=/, $pairs);
		$key = $keyvalue[0];
		$value = $keyvalue[1];
		$hash{ $key } = $value; 
		if($count==1){
		$check .= $value;
		}
		else{
		$check .= md5_hex($value);
		}
		open (FILE,"password.txt");
		while (<FILE>) {
			if($_ eq $check){
				
				open (FILE,"appointment.html");
				while (<FILE>) {
					print $_;
				}
				print '<input type="text" name="username" value="user" maxlength="100" />'; 
				close(FILE);
				$found++;
				last;
			}
		}
		close(FILE);
		$check .= '=';
	}
	if($found==0){
print <<END_OF_PRINTING; 
Error user and password doesn't match.
END_OF_PRINTING
	}
}
